import React from "react";

import PageContent from '../../PageContent'

import { ajax ,showResultMessage,isNull,isNotNull,batchAjax,setStoreItem,getStoreItem} from '../../common';

import { Form, Input, Icon, Divider,Collapse } from 'antd';

import { Link } from 'react-router-dom';

import ConfigProductUIComponentDataSourcePanel from './ConfigProductUIComponentDataSourcePanel';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UIFormView from '../../uicomponents/UIFormView';

import UIIcon from '../../uicomponents/UIIcon';

import UIView from '../../uicomponents/UIView';

import UIToolbar from '../../uicomponents/UIToolbar';

import ImportProductUITablePanel from './ImportUIDataFilePanel';

import ExportProductUITablePanel from './ExportUIDataFilePanel';

import ImportProductModelPropertiesPanel from './ImportProductModelPropertiesPanel';

const FormItem = Form.Item;

const Panel = Collapse.Panel;
/** 
 *产品UI表格管理
*/
export default class ProductUITableManageApp extends React.Component {

    state = {
		tableSearchValues : getStoreItem('uiTableSearchValues',{}),
	}

	onTableSearchValueChange = (values) => {
		this.setState({tableSearchValues : values});
		setStoreItem('uiTableSearchValues',values);
	}

	render() {

        /**路由设置 */
		const pageContentMap = {
			'/': {
				text: '',
				icon: '',
				getComponent: (owner, props) => {
					return (<ProductUITableListPanel {...props} 
						tableSearchValues={this.state.tableSearchValues} 
						onTableSearchValueChange={this.onTableSearchValueChange}
						key="uiTableList" 
						
						/>
						);
				}
			},
			'/editUITableFields': {
				text: '编辑表格字段',
				icon: 'edit',
				getComponent: (owner, props) => {
					return (<EditProductUITableFieldListPanel {...props} key="editTableFields" />);
				}
			},
			'/importDataFiles': {
				text: '导入UI表格',
				icon: 'sign-in-alt',
                getComponent: (owner, props) => {
                    return <ImportProductUITablePanel {...props} importURL="PRODUCT/UI/import/importUITableFile/" pageTitle="导入UI表格" key="importTables"/>;
                }
			},
			'/exportDataFiles': {
				text: '导出UI表格',
				icon: 'sign-out-alt',
                getComponent: (owner, props) => {
                    return <ExportProductUITablePanel {...props} exportURL="PRODUCT/UI/export/exportUITableFile/" pageTitle="导出UI表格" key="exportTables"/>;
                }
			},
        }

		return (
			<PageContent {...this.props} pageInstance={this} contentMap={pageContentMap}>
			</PageContent>
		);
	}
}



/** 
 * 产品UI表格列表
*/
class ProductUITableListPanel extends React.Component {

	constructor(props) {
		super(props);
		this.state = {
            formTitle: '',
		}
    }

	actionHandler = (actionEvent) => {

		const { selectTableIds, tableListRef, tableFormRef } = this;

		return {
			refresh : () => {
				tableListRef.loadData();
			},
			addNew : () => {
				this.setState({ formTitle: '新增产品UI表格'});
				setTimeout(() => {
					tableFormRef.openModal(() => {
						const initParams = getStoreItem('uiTableSearchValues',{});
						if(isNotNull(initParams['domainId'])){
							tableFormRef.setFormData({domainId : initParams['domainId']});
						}
					});
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑产品UI表格' });
				setTimeout(() => {
					tableFormRef.openModal(() => {
						tableFormRef.setFormData(actionEvent.params);
					});
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (actionEvent.params != null) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectTableIds;
				}

				ajax('PRODUCT/UI/productUITable/batchDelete', { ids: selectedIds }, (data) => {
					tableListRef.loadData();
				});
			},
			doSave : () => {
				tableFormRef.getFormData((formData) => {

					ajax('PRODUCT/UI/productUITable/save', formData, (data) => {
						tableFormRef.closeModal();
						tableListRef.loadData();
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				});
			}
		};
	}

	render() {

		const tableProps = {
            ref: (inst) => { this.tableListRef = inst },
			history : this.props.history,
			title : "UI表格",
			extra : (<UIToolbar history={this.props.history} actionGroupId="ProductUI:productUIDataPanelActionGroup" actionHandler={this.actionHandler}/>),
			actionHandler: this.actionHandler,
			actionGroupId: 'ProductUI:productUITableListActionGroup',
			rowActionGroupId: 'ProductUI:productUITableRowActionGroup',
			tableConfigId: 'ProductUI:productUITableTable',
			dataUrl: 'PRODUCT/UI/productUITable/query',
			selectMode: 'multi',
            searchFormId: 'ProductUI:productUITableSearchForm',
            initSearchValues : this.props.tableSearchValues,
			autoLoad: true,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('edit');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('edit');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectTableIds = selectRowKeys;
				}
            ,
            onSearchData : (changedValues) => {
				
				if(this.props.onTableSearchValueChange){
					this.props.onTableSearchValueChange(changedValues)
				}
			}
		};

		const tableFormProps = {
			ref: (inst) => { this.tableFormRef = inst },
			formConfigId: 'ProductUI:productUITableForm',
			actionGroupId: 'ProductUI:saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		};

		return (
			<UIDataTableView {...tableProps}>
				<UIFormView {...tableFormProps} />
			</UIDataTableView>
		);
	}
}

/**
 * 编辑表格字段
 */
class EditProductUITableFieldListPanel extends React.Component {
    constructor(props) {
		super(props);
		this.state = {
			formTitle: '',
			pageTitle : '',
			tableField : null,
		}
	}
	
	componentDidMount(){
		this.table = this.props.location.state;
		this.setState({pageTitle : '编辑[' + this.table.code +   ']表格字段'});
		this.loadTableFields(this.table.id);
	}

    loadTableFields = (tableId) => {
		
        this.tableFiledListRef.loadData({tableId : tableId});
    }

    actionHandler = (actionEvent) => {

		const { selectIds, tableFieldEditFormRef, tableFiledListRef, fieldDataSourceViewRef, fieldDataSourceRef, fieldDataIconViewRef, importModelPropertyViewRef, fieldDataIconRef, importModelPropertyRef, fieldBatchEditFormRef,table } = this;

		const {tableField} = this.state;

		return {
			refresh : () => {
				tableFiledListRef.loadData({tableId :table.id});
			},
			addNew : () => {
				this.setState({ formTitle: '添加表格字段'});
				
				setTimeout(() => {
					tableFieldEditFormRef.openModal();
				});
			},
			doEdit : () => {
				this.setState({ formTitle: '编辑表格字段',tableField : actionEvent.params  });
				
				setTimeout(() => {
					tableFieldEditFormRef.openModal(() => {
						tableFieldEditFormRef.setFormData(actionEvent.params);
					});
				});
			},
			importTableFields : () => {
				importModelPropertyViewRef.openModal();
			},
			batchEditProperty : () => {
				fieldBatchEditFormRef.openModal();
			},
			setTableFieldDataSource : () => {
				this.setState({ tableField : actionEvent.params });
				setTimeout(() => {
					fieldDataSourceViewRef.openModal();
				});
			},
			setTableFieldIcons: () => {
				this.setState({ tableField : actionEvent.params });
				setTimeout(() => {
					fieldDataIconViewRef.openModal();
				});
			},
			doDelete : () => {
				let selectedIds = null;

				if (isNull(actionEvent.params) !== true) {
					selectedIds = [actionEvent.params.id];
				}
				else {
					selectedIds = selectIds;
				}

				ajax('PRODUCT/UI/productUITableField/batchDelete', { ids: selectedIds }, (data) => {
					tableFiledListRef.loadData({tableId :table.id});
				});
			},
			doSave : () => {

				if(tableFieldEditFormRef.isOpend()){
					tableFieldEditFormRef.getFormData((formData) => {
						formData.tableId = table.id;
						ajax('PRODUCT/UI/productUITableField/save', formData, (data) => {
							tableFieldEditFormRef.closeModal();
							tableFiledListRef.loadData({tableId :table.id});
							showResultMessage({
								success: true,
								message: 'message.saveSuccess',
							});
						});
					});
				}
				else if(fieldDataSourceViewRef.isOpend()){

					fieldDataSourceRef.getDataSource((dataSource) => {
						tableField.listDataSource = isNull(dataSource) ? '' : dataSource.id;
						ajax('PRODUCT/UI/productUITableField/save',tableField,(data) => {
							fieldDataSourceViewRef.closeModal();
							tableFiledListRef.loadData({tableId :table.id});
						});
					});
				}
				else if(fieldDataIconViewRef.isOpend()){

					fieldDataIconRef.getFieldIcons( (fieldIcons) => {
						
						const columnIcons = fieldIcons.map( (fieldIcon) => {
							return {
								columnId : tableField.id,
								dataValue : fieldIcon.value,
								dataIcon : fieldIcon.icon.imageCode,
							};
						} );

						ajax('PRODUCT/UI/productUITableFieldIcon/setTableColumnIcons/' + tableField.id,columnIcons,(data) => {
							fieldDataIconViewRef.closeModal();
							tableFiledListRef.loadData({tableId :table.id});
						},'application/json');

					} );
				}
				else if(importModelPropertyViewRef.isOpend()){
					
					const fields =  importModelPropertyRef.getSelectProperties();
					const urls = [];
					const tableColumns = fields.map( (field,index) => {
						urls.push('PRODUCT/UI/productUITableField/save');
						return {
							tableId : table.id,
							width : '100',
							code : field.property,
							title : field.propertyTitle,
							showValue : true,
							sortIndex : index + 1,
						}
					} );

					batchAjax(urls, tableColumns, (data) => {
						importModelPropertyViewRef.closeModal();
						tableFiledListRef.loadData({tableId :table.id});
						showResultMessage({
							success: true,
							message: 'message.saveSuccess',
						});
					});
				}
				else if(fieldBatchEditFormRef.isOpend){
					fieldBatchEditFormRef.getFormData(formData => {
						
						const editData = {};
						for(let key in formData){
							if(isNotNull(formData[key])){
								editData[key] = formData[key];
							}
						}
						
						const tableFiledDataList = tableFiledListRef.getSelectedDatas();
						const urls = [];
						const tableFields = tableFiledDataList.map( (field) => {
							urls.push('PRODUCT/UI/productUITableField/save');
							return {...field,...editData};
						} );

						batchAjax(urls, tableFields, (data) => {
							fieldBatchEditFormRef.closeModal();
							tableFiledListRef.loadData({tableId : table.id});
							showResultMessage({
								success: true,
								message: 'message.saveSuccess',
							});
						});
					});
				}

			},
			moveDown : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex < tableFiledListRef.getListData().length){
					rowData.sortIndex = rowData.sortIndex + 1;
					ajax('PRODUCT/UI/productUITableField/save',rowData,(data) => {
						tableFiledListRef.loadData({tableId :table.id});
					});
				}
			},
			moveUp : () => {
				const rowData = actionEvent.params;
				if(rowData.sortIndex > 1){
					rowData.sortIndex = rowData.sortIndex - 1;
					ajax('PRODUCT/UI/productUITableField/save',rowData,(data) => {
						tableFiledListRef.loadData({tableId :table.id});
					});
				}
			},
			
		};
	}

	render () {

		const {tableField} = this.state;

		const tableProps = {
			bordered : false,
			title : this.state.pageTitle,
			ref: (inst) => { this.tableFiledListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'ProductUI:productUITableFieldListActionGroup',
			rowActionGroupId: 'ProductUI:productUITableFieldRowActionGroup',
			tableConfigId: 'ProductUI:productUITableFieldTable',
			dataUrl: 'PRODUCT/UI/productUITableField/query',
			selectMode: 'multi',
			autoLoad: false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('delete');
					topToolBar.enable('batchEditProperty');
				}
				else {
					topToolBar.disable('delete');
					topToolBar.disable('batchEditProperty');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		return (
			<UIDataTableView extra={<Link to="/">返回</Link>} {...tableProps}>
				<UIFormView formConfigId="ProductUI:productUITableFieldForm" 
					inPop={true} destroyOnClose={true} title={this.state.formTitle} ref={(inst) => this.tableFieldEditFormRef = inst} 
					 actionGroupId={'saveActionGroup'} actionHandler={this.actionHandler}
					/>
				<UIFormView formConfigId="ProductUI:productUITableFieldBatchEditForm"
					inPop={true} destroyOnClose={true} title="批量设置属性" ref={(inst) => this.fieldBatchEditFormRef = inst} 
					 actionGroupId={'ProductUI:saveActionGroup'} actionHandler={this.actionHandler}
					/>
				<UIView width={1000} inPop={true} destroyOnClose={true} title="设置数据源" ref={(inst) => this.fieldDataSourceViewRef = inst}
					bordered={false} actionGroupId={'ProductUI:saveActionGroup'}
					actionHandler={this.actionHandler}>
					<ConfigProductUIComponentDataSourcePanel  datasourceId={isNull(tableField) ? '' : tableField.listDataSource} ref={(inst) => this.fieldDataSourceRef = inst}/>
				</UIView>
				<UIView width={1000} inPop={true} destroyOnClose={true} title="设置数据图标" ref={(inst) => this.fieldDataIconViewRef = inst}
					bordered={false} actionGroupId={'ProductUI:saveActionGroup'}
					actionHandler={this.actionHandler}>
					<ConfigTableFieldIconsPanel tableField={tableField} ref={(inst) => this.fieldDataIconRef = inst}/>
				</UIView>
				<UIView width={600} inPop={true} destroyOnClose={true} title="导入对象属性" ref={(inst) => this.importModelPropertyViewRef = inst}
					bordered={false} actionGroupId={'ProductUI:saveActionGroup'}
					actionHandler={this.actionHandler}>
					<ImportProductModelPropertiesPanel ref={(inst) => this.importModelPropertyRef = inst}/>
				</UIView>
			</UIDataTableView>
		);
	}
}

/**
 * 配置字段数据图标
 */
class ConfigTableFieldIconsPanel extends React.Component {

	state = {
		fieldIcons : [],
	}

	componentDidMount(){
		const {tableField} = this.props;
		if(isNull(tableField) === false){
			ajax('PRODUCT/UI/productUITableFieldIcon/query',{tableFieldId : tableField.id},(data) => {
				this.setState({fieldIcons : data.records});
			});
		}
				
	}

	actionHandler = (actionEvent) => {

		const { selectIds, imageListRef,fieldIconsRef } = this;

		return {
			chooseUIImage : () => {
				const selectedIcons = imageListRef.getSelectedDatas();

				fieldIconsRef.add(selectedIcons);
			
			},
		}
	}

	getFieldIcons = (cb) => {
		this.fieldIconsRef.getFieldIcons(cb);
	}

	render() {
		const {fieldIcons} = this.state;

		const imageTableProps = {
			ref: (inst) => { this.imageListRef = inst },
			actionHandler: this.actionHandler,
			actionGroupId: 'ProductUI:chooseProductUIImageListActionGroup',
			tableConfigId: 'ProductUI:productUIImageTable',
			dataUrl: 'PRODUCT/UI/productUIImage/query',
			selectMode: 'multi',
			searchFormId: 'ProductUI:productUIImageSearchForm',
			autoLoad: true,
			bordered : false,
			setToolbarState: (topToolBar, selectedIds) => {
				if (selectedIds.length > 0) {
					topToolBar.enable('add');
				}
				else {
					topToolBar.disable('add');
				}
			},
			onSelectChange:
				(selectRowKeys) => {
					this.selectIds = selectRowKeys;
				}
			,
		};

		return (
			
			<React.Fragment>
				<WrappedDynamicFieldSet fieldIcons={fieldIcons} wrappedComponentRef={(inst) => this.fieldIconsRef = inst}/>
				<Collapse >
					<Panel header="可选图标列表" key="1">
						<UIDataTableView {...imageTableProps}/>
					</Panel>
				</Collapse>
			</React.Fragment>
		);
	}
}

class DynamicFieldSet extends React.Component {

	remove = (k) => {
	  const { form } = this.props;
	  // can use data-binding to get
	  const fieldIcons = form.getFieldValue('fieldIcons');
	   
	  // can use data-binding to set
	  form.setFieldsValue({
		fieldIcons: fieldIcons.filter(fieldIcon => fieldIcon.key !== k),
	  });
	}
  
	add = (icons) => {
	  const { form } = this.props;
	  // can use data-binding to get
	  const fieldIcons = form.getFieldValue('fieldIcons');
	  const addFieldsIcons = icons.map((icon,index) => {
		return {
			key : fieldIcons.length + index,
			value : '',
			icon : icon
		};
	  });
	  const newFieldsIcons = fieldIcons.concat(addFieldsIcons);
	  // can use data-binding to set
	  // important! notify form to detect changes
	  form.setFieldsValue({
		fieldIcons: newFieldsIcons,
	  });
	}

	getFieldIcons = (cb) => {
		this.props.form.validateFields((err, values) => {
			if (!err) {
			  console.log('Received values of form: ', values);
			  values.names.map( (value,index) => {
				values.fieldIcons[index].value = value;
			  } );

			  if(cb){
				cb(values.fieldIcons);
			  }
			}
		  });
	}
  
	render() {
		
		const { getFieldDecorator, getFieldValue } = this.props.form;
		  
		const {fieldIcons,form} = this.props;

		if(isNull(fieldIcons) === false){
			const icons = fieldIcons.map((fieldIcon,index) => {
				return {
					key : index,
					value : fieldIcon.dataValue,
					icon : {imageCode : fieldIcon.dataIcon}
				}
			});
			
			getFieldDecorator('fieldIcons', { initialValue: icons });
		}
		else{
			getFieldDecorator('fieldIcons', { initialValue: [] });
		}

	  	const formItemLayout = {
			labelCol: {
			xs: { span: 24 },
			sm: { span: 4 },
			},
			wrapperCol: {
			xs: { span: 24 },
			sm: { span: 20 },
			},
	  	};
	  
	  const tableFieldIcons = getFieldValue('fieldIcons');
	  const formItems = tableFieldIcons.map((fieldIcon, index) => {
		return (
		  <FormItem
			{...formItemLayout}
			label='数据'
			required={false}
			key={fieldIcon.key}
		  >
			{getFieldDecorator(`names[${fieldIcon.key}]`, {
			  validateTrigger: ['onChange', 'onBlur'],
			  initialValue : fieldIcon.value,
			  rules: [{
				required: true,
				whitespace: true,
				message: "请输入数据，‘*’ 表示所有数据",
			  }],
			})(
			  <Input placeholder="请输入数据，‘*’ 表示所有数据" style={{ width: '40%', marginRight: 8 }} />
			)}
			对应图标 ： <UIIcon icon={fieldIcon.icon.imageCode}/>
			<Divider key={fieldIcon.key} type="vertical" />
			 <Icon
			 	color="#eb2f96"
				type="minus-circle-o"
				onClick={() => this.remove(fieldIcon.key)}
			  />
		  </FormItem>
		);
	  });
	  return (
		<Form>
		  {formItems}
		</Form>
	  );
	}
  }

const WrappedDynamicFieldSet = Form.create()(DynamicFieldSet);